/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.event.impl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import cgl.narada.event.TemplateInfo;
import cgl.narada.event.TemplateProfileAndSynopsisTypes;


/** Provides information regarding a template 

    @author Shrideep Pallickara
    $Date$
    $Revision$
 */

public class TemplateInfoImpl implements  TemplateInfo {
  private int templateId=0;

  private int templateType=0;

  private Object template = null;
  
  private boolean hasAllEncompassingConstraint=false;
  private Object allEncompassingConstraint = null;
  private String moduleName = "TemplateInfoImpl: ";

  public TemplateInfoImpl(int templateId, int templateType, 
			  Object template) {
    this.templateId = templateId;
    this.templateType = templateType;
    this.template = template;
  }

   public TemplateInfoImpl(int templateId, int templateType, 
			   Object template, Object allEncompassingConstraint) {
    this.templateId = templateId;
    this.templateType = templateType;
    this.template = template;
    this.allEncompassingConstraint = allEncompassingConstraint;
    hasAllEncompassingConstraint = true;
  }
  
  
  /** Returns the template ID associated with this template */
  public int getTemplateId() {
    return templateId;
  }

  /** Returns the template type*/
  public int getTemplateType() {
    return templateType;
  }
  
  /** Returns the template */
  public Object getTemplate() {
    return template;
  }

  /** Returns the all encompassing constraint associated with this template */
  public boolean hasAllEncompassingConstraint() {
    return hasAllEncompassingConstraint;
  }

  /** Returns the all encompassing constraint, to ensure receipt of every event
      published to this template */
  public Object getAllEncompassingConstraint() {
    return allEncompassingConstraint;
  }


  /**
     Compares two objects for equality. Returns a boolean that indicates
     whether this object is equivalent to the specified object. This method
     is used when an object is stored in a hashtable.
     @param obj the Object to compare with
     @return true if these Objects are equal; false otherwise.
     @see java.util.Hashtable */
  public boolean equals(Object obj) {
    TemplateInfo compareWith = (TemplateInfo)obj;
    if (templateId == compareWith.getTemplateId()) {
      if (templateType == compareWith.getTemplateType()) {
	return true;
      }
    }
    return false;
  }

  /**Generates a hash code for the receiver. This method is supported 
     primarily for hash tables, such as those provided in java.util.
     If two objects are equal (equals(Object) returns true) they must have the 
     same hash code
     @return an integer hash code for the receiver */
  public int hashCode() {
    return templateId;
  }
  

  public String toString() {
    String stringRep = "TenplateId=" + templateId + ", template type = " +
      templateType + ", Encompassing Constraint = " + 
      allEncompassingConstraint;
    
    return stringRep;
  }

  public TemplateInfoImpl(byte[] marshalledBytes) {
    ByteArrayInputStream baInputStream = 
      new ByteArrayInputStream(marshalledBytes);
    DataInputStream din = new DataInputStream(baInputStream);

    try {
      templateId = din.readInt();
      templateType = din.readInt();

      byte[] templateBytes = new byte[din.readInt()];
      din.readFully(templateBytes);
      template = recreateObject(templateBytes);

      hasAllEncompassingConstraint = din.readBoolean();
      
      if (hasAllEncompassingConstraint) {
	byte[] constraintBytes =  new byte[din.readInt()];
	din.readFully(constraintBytes);
	allEncompassingConstraint = recreateObject(constraintBytes);
      }

    } catch (Exception e) {
      System.out.println(moduleName + "Error while un-marshalling" + e);
    }/** end try-catch block*/
 }
  
  private Object recreateObject(byte[] objectBytes) 
    throws Exception {
    ByteArrayInputStream baInputStream = 
      new ByteArrayInputStream(objectBytes);
    ObjectInputStream objIn = new ObjectInputStream(baInputStream);
    Object object = objIn.readObject();
    return object;
  }

   /** Get a marshalled representation of the template info */
  public byte[] getBytes() {
    ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream();
    DataOutputStream dout = new DataOutputStream(baOutputStream);
    byte[] marshalledBytes= null;
    try {
      dout.writeInt(templateId);
      dout.writeInt(templateType);
     
      byte[] templateBytes = getByteRepresentation(template);
      dout.writeInt(templateBytes.length);
      dout.write(templateBytes);

      dout.writeBoolean(hasAllEncompassingConstraint);

      if (hasAllEncompassingConstraint) {
	byte[] constraintBytes = 
	  getByteRepresentation(allEncompassingConstraint);
	dout.writeInt(constraintBytes.length);
	dout.write(constraintBytes);
      }
      
      dout.flush();
      marshalledBytes = baOutputStream.toByteArray();
    } catch (Exception e) {
      System.out.println(moduleName + "Error while marshalling" + e);
    } /** end try-catch block*/
    
    return marshalledBytes;
  }

  private byte[] getByteRepresentation(Object object) throws IOException {
    ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream();
    ObjectOutputStream objOut = new ObjectOutputStream(baOutputStream);
    objOut.writeObject(object);
    objOut.flush();
    byte[] objectBytes = baOutputStream.toByteArray();
    return objectBytes;
  }


  
  public static void main(String[] args) {
    TemplateInfoImpl templateInfo = 
      new TemplateInfoImpl(12345, TemplateProfileAndSynopsisTypes.STRING,
			   "Movie/Casablanca", "Humprey/Bogart");
    
    TemplateInfoImpl templateInfo2 = 
      new TemplateInfoImpl(templateInfo.getBytes());
    System.out.println(templateInfo2);

  }
  

}
